<?php

namespace addons\member\user\controller;

class MemberArea extends \web\user\controller\AddonUserBase{
    
    public function index(){
        return $this->fetch();
    }
    
    public function loadList(){
        $keyword = $this->_get('keyword');
        $status = $this->_get('status');
        $filter = ' 1=1 ';
        if($keyword!=''){
            $filter .= ' and username like "%'.$keyword.'%" ';
        }
        if($status!=''){
            $filter .= ' and status = '.$status.' ';
        }
        $m = new \addons\member\model\MemberArea();
        $fileds = '*';
        $order = 'id desc';
        $total = $m->getTotal($filter);
        $rows = $m->getDataList($this->getPageIndex(), $this->getPageSize(), $filter, $fileds, $order);

        return $this->toDataGrid($total, $rows);
    }
    
    public function edit(){
        $m = new \addons\member\model\MemberArea();
        if(IS_POST){
            $data = $_POST;
            if($data['id']){
                $m->save($data);
                //添加管理日志
                $this->addLog(self::LOG_EDIT,'修改会员资料',$data, $data['id']);
                return $this->successData();
            }else{
                return $this->failData('用户id为空');
            }
        }else{
            $this->assign('id', $this->_get('id'));
            $this->setLoadDataAction('loadData');
            return $this->fetch();
        }
    }
    

    /**
     * 审核
     */
    public function examine(){
        $id = $this->_post('id');
        $status = $this->_post('status')==1?1:2;
        $m = new \addons\member\model\MemberArea();
        $data = $m->getDetail($id);
        if($data['status']!=0) return $this->failData('参数错误');
        try{
            $m->startTrans();
            $res = $m->where('id',$id)->update(['status'=>$status,'update_time'=>NOW_DATETIME]);
            if(!$res){
                $m->rollback();
                return $this->failData('操作失败');
            }
            if($status==1){
                $userM = new \addons\member\model\MemberAccountModel();
                $res = $userM->where('id',$data['user_id'])->update(['is_agent'=>1,'region_id'=>$data['area_id']]);
                if(!$res){
                    $m->rollback();
                    return $this->failData('更新用户失败');
                }
            }
            $m->commit();
            return $this->successData();
        } catch (\Exception $ex) {
            $m->rollback();
            return $this->failData($ex->getMessage());
        }
    }

    public function loadData() {
        $id = $this->_get('id');
        $m = new \addons\member\model\MemberArea();
        $data = $m->getDetail($id);
        return $data;
    }
    

}


